package org.speed.jdk;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class DelayQueueDemo {
	
	
	public static void main(String[] args) throws Exception {
		
		Task item1 = new Task("item1", 5, TimeUnit.SECONDS);
		Task item2 = new Task("item2",10, TimeUnit.SECONDS);
		Task item3 = new Task("item3",15, TimeUnit.SECONDS);
		Task item4 = new Task("item4",20, TimeUnit.SECONDS);
        DelayQueue<Task> queue = new DelayQueue<>();
        queue.put(item1);
        queue.put(item2);
        queue.put(item3);
        queue.put(item4);
        System.out.println("begin time:" + LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        
        
        
        ExecutorService pools = Executors.newFixedThreadPool(2);
        
        Executors.newScheduledThreadPool(1);
        
        
        pools.submit(new Callable<Object>() {

			@Override
			public Object call() throws Exception {
				return null;
			}
		});
        
        Task task = null;
        while((task = queue.take()) != null ) {
        	Task take = task;
        	pools.execute(new Runnable() {
				@Override
				public void run() {
					System.out.format(Thread.currentThread().getName() + "-name:{%s}, time:{%s}\n",take .name, LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME));
				}
			});
        }
        
        
        
        
		
	}
	
	
	static class TimeWheel {
		
		long startTime = 0 ;
		
		long internal = 1;
		
		long currentTime = 0;
		
		
		DelayQueue<Task> queue;
		
		
		void add(long time) {
			long delayTime = System.currentTimeMillis() + time;
			
			queue.add(null);
			
			
		}
		
		void clock() {
			
			startTime = System.currentTimeMillis();
			while(true) {
				try {
					Task task = queue.poll(internal,TimeUnit.SECONDS);
					currentTime += internal;
					
					
					
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
			}
			
			
		}
		
		
		
	}
	
	
	static class Task implements Delayed {

		private long time;
		private String name;
		
		public Task(String name, long time, TimeUnit unit) {
	        this.name = name;
	        this.time = System.currentTimeMillis() + (time > 0? unit.toMillis(time): 0);
	    }
		
		@Override
		public int compareTo(Delayed o) {
			Task item = (Task) o;
	        long diff = this.time - item.time;
	        if (diff <= 0) {
	            return -1;
	        }else {
	            return 1;
	        }
		}

		@Override
		public long getDelay(TimeUnit unit) {
			return time - System.currentTimeMillis();
		}
		
		
		
	}

}
